package algocasts;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class P65_PreorderTraversal {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
    }

    private void preorder(TreeNode root, List<Integer> result) {
        if (root == null) return;
        result.add(root.val);
        preorder(root.left, result);
        preorder(root.right, result);
    }

    // Time: O(n)  Space: O(n)
    public List<Integer> preorderTraversal_Recursive(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        preorder(root, result);
        return result;
    }

    // Time: O(n) Space:O(n)
    public List<Integer> preorderTraversal_Iterative(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();

        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                result.add(root.val);
                stack.add(root);
                root = root.left;
            }
            root = stack.pop().right;
        }
        return result;
    }

    // Time: O(n)  Space: O(n)
    public List<Integer> preorderTraversal_Iterative2(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            result.add(node.val);
            if (node.right != null) stack.push(node.right);
            if (node.left != null) stack.push(node.left);
        }
        return result;
    }
}
